package Server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

import Protocol.user.BasePersonInfo;
import Protocol.user.Login_Q;
import Protocol.user.Login_R;
import Protocol.user.Logout_R;

public class ServerListener implements Runnable {
	private Server                 server;
	private Socket                 clientSocket;
	private Login_R                clientInfo;
	private ObjectInputStream      objectIn;
	private ObjectOutputStream     objectOut;
	private boolean                isOnline;
	
	private ServerHandler         handler;
	
	ServerListener(Server  ser, Socket  soc) {
		server = ser;
		clientSocket = soc;
		clientInfo = null;
		isOnline = true;
		try {
			objectIn = new ObjectInputStream(clientSocket.getInputStream());
			objectOut = new ObjectOutputStream(clientSocket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean isOnline() {
		return isOnline;
	}
	public void setOnline(boolean isOnline) {
		this.isOnline = isOnline;
	}
	synchronized void disconnect() {
		/*server.decClientNumber();
		server.getUserSocketMap().remove(clientInfo);*/
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		handler = new ServerHandler(this);
		Object       objectReceived = null;
		
		while (server.isServerRunning() & isOnline) {
			try {
				objectReceived = objectIn.readObject();
				System.out.println("Received Object from client : "+ objectReceived);
				
				handler.handleObjectMsg(objectReceived);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public Server getServer() {
		return server;
	}

	public void setServer(Server server) {
		this.server = server;
	}

	public ObjectInputStream getObjectIn() {
		return objectIn;
	}

	public ObjectOutputStream getObjectOut() {
		return objectOut;
	}
	public Socket  getClientSocket() {
		return this.clientSocket;
	}

}
